package com.perfect.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class CustomerBlockExceptionHandler implements BlockExceptionHandler {



    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {

        String msg=null;
        if(e instanceof FlowException){
            msg="接口限流了";
        }

        if(e instanceof DegradeException){
            msg="服务降级了";
        }

        if(e instanceof ParamFlowException){
            msg="热点参数限流了";
        }

        if(e instanceof SystemBlockException){
            msg="触发系统保护规则了";
        }

        if(e instanceof AuthorityException){
            msg="系统保护规则不通过";
        }

        System.out.println(msg);
        response.setStatus(429);
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        out.print(msg);
        out.flush();
        out.close();
    }


}
